<?php

/**
 *
 * @author Zhang Di <zhangdi_me@163.com>
 */

namespace yiiwiki\storage;

use yii\base\Exception;
use yii\base\InvalidConfigException;

/**
 * 本地存储
 *
 * @package yiiwiki\storage
 */
class LocalStorage extends BaseStorage
{
    /**
     * @var 存储文件的根目录
     */
    public $basePath;

    public function init()
    {
        if (!isset($this->basePath)) {
            throw new InvalidConfigException('请配置 LocalStorage::basePath .');
        }
    }

    /**
     * 将内容写入文件
     *
     * @param string $filename
     * @param string $content
     * @return mixed
     */
    public function write($filename, $content)
    {
        $realPath = $this->getRealPath($filename);
        $dir = dirname($realPath);
        if ($this->dirExists($dir, true)) {
            return file_put_contents($realPath, $content);
        } else {
            return false;
        }
    }

    /**
     * 上传文件
     *
     * @param string $srcFilename
     * @param string $distFilename
     * @return mixed
     */
    public function upload($srcFilename, $distFilename)
    {
        if (file_exists($srcFilename)) {
            $realPath = $this->getRealPath($distFilename);
            $this->dirExists(dirname($realPath));
            return copy($srcFilename, $realPath);
        } else {
            $this->errorCode = self::ERROR_NO_SOURCE_FILE;
            $this->errorMessage = "\$srcFilename '$srcFilename' 不存在。";
            return false;
        }
    }

    /**
     * 获取文件内容
     *
     * @param string $filename
     * @return mixed
     */
    public function get($filename)
    {
        if ($this->exists($filename)) {
            $realPath = $this->getRealPath($filename);
            return file_get_contents($realPath);
        } else {
            throw new Exception("$filename 不存在。");
        }
    }

    /**
     * 文件是否存在
     *
     * @param string $filename
     * @return boolean
     */
    public function exists($filename)
    {
        $realPath = $this->getRealPath($filename);
        return file_exists($realPath);
    }

    /**
     * 根据 $filename 获取文件真是路径
     *
     * @param string $path
     * @return string
     */
    protected function getRealPath($filename)
    {
        return $this->basePath . DIRECTORY_SEPARATOR . $filename;
    }

    /**
     * 文件件是否存在
     *
     * @param string $dir
     * @param boolean $createIfNotExists 文件夹不存在时是否创建，默认为 false 不创建
     * @return boolean
     */
    public function dirExists($dir, $createIfNotExists = false)
    {
        if (!file_exists($dir)) {
            if ($createIfNotExists) {
                return mkdir($dir, 0777, true);
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    /**
     * @inheritdoc
     */
    public function delete($filename)
    {
        if ($this->exists($filename)) {
            return unlink($this->getRealPath($filename));
        } else {
            return true;
        }
    }

} 